Passed
Push — master ( 1a6db4...d22713 )
by Muhammad Dyas
01:40
created

state.ts ➔ getStateFromCard   A

Complexity

Conditions 5

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 8
rs 9.3333
c 0
b 0
f 0
cc 5
1
import {ClosableType, PollForm, PollFormInputs, PollState} from './interfaces';
2
import {chat_v1 as chatV1} from '@googleapis/chat';
3
import {MAX_NUM_OF_OPTIONS} from '../config/default';
4
import {callMessageApi} from './api';
5
6
/**
7
 * Add a new option to the state(like DB)
8
 *
9
 * @param {string} option - the new option name
10
 * @param {object} state - the current message state
11
 * @param {string} creator - who add the new option
12
 * @returns {void} card
13
 */
14
export function addOptionToState(option: string, state: PollState, creator = '') {
15
  const choiceLength = state.choices.length;
16
  state.choices.push(option);
17
  if (state.choiceCreator === undefined) {
18
    state.choiceCreator = {[choiceLength]: creator};
19
  } else {
20
    state.choiceCreator[choiceLength] = creator;
21
  }
22
}
23
24
export function getStateFromCard(event: chatV1.Schema$DeprecatedEvent) {
25
  const card = event.message?.cardsV2?.[0]?.card as chatV1.Schema$GoogleAppsCardV1Card;
26
  if (!card) {
27
    throw new ReferenceError('no valid card in the event');
28
  }
29
  return getStateFromCardName(card) || getStateFromParameter(event) || getStateFromCardWhenNoHeader(card) ||
30
    getStateFromCardWhenHasHeader(card);
31
}
32
33
function getChoicesFromInput(formValues: PollFormInputs) {
34
  const choices = [];
35
  for (let i = 0; i < MAX_NUM_OF_OPTIONS; ++i) {
36
    const choice = formValues[`option${i}`]?.stringInputs!.value![0]!.trim();
37
    if (choice) {
38
      choices.push(choice);
39
    }
40
  }
41
  return choices;
42
}
43
44
function getStringInputValue(input: chatV1.Schema$Inputs) {
45
  if (!input) {
46
    return '';
47
  }
48
  return input.stringInputs!.value![0];
49
}
50
51
export function getConfigFromInput(formValues: PollFormInputs) {
52
  const state: PollForm = {topic: '', choices: []};
53
  state.topic = getStringInputValue(formValues.topic).trim() ?? '';
54
  state.anon = getStringInputValue(formValues.is_anonymous) === '1';
55
  state.optionable = getStringInputValue(formValues.allow_add_option) === '1';
56
  state.type = parseInt(getStringInputValue(formValues.type) || '1') as ClosableType;
57
  state.autoClose = getStringInputValue(formValues.is_autoclose) === '1';
58
  state.autoMention = getStringInputValue(formValues.auto_mention) === '1';
59
  state.closedTime = parseInt(formValues.close_schedule_time?.dateTimeInput!.msSinceEpoch ?? '0');
60
  state.choices = getChoicesFromInput(formValues);
61
  state.voteLimit = parseInt(getStringInputValue(formValues.vote_limit) || '1');
62
  return state;
63
}
64
65
function getStateFromCardWhenNoHeader(card: chatV1.Schema$GoogleAppsCardV1Card) {
66
  return card.sections?.[0].widgets?.[0].decoratedText?.button?.onClick?.action?.parameters?.[0]?.value;
67
}
68
69
function getStateFromCardWhenHasHeader(card: chatV1.Schema$GoogleAppsCardV1Card) {
70
  // when has header the first section is header
71
  return card.sections?.[1].widgets?.[0].decoratedText?.button?.onClick?.action?.parameters?.[0]?.value;
72
}
73
74
export function getStateFromCardName(card: chatV1.Schema$GoogleAppsCardV1Card) {
75
  // when has header the first section is header
76
  return card.name;
77
}
78
79
function getStateFromParameter(event: chatV1.Schema$DeprecatedEvent) {
80
  const parameters = event.common?.parameters;
81
82
  return parameters?.['state'];
83
}
84
85
export async function getStateFromMessageId(eventId: string): Promise<PollState> {
86
  const request = {
87
    name: eventId,
88
  };
89
  const apiResponse = await callMessageApi('get', request);
90
  const currentState = getStateFromCardName(apiResponse.data.cardsV2?.[0].card ?? {});
91
  if (!currentState) {
92
    console.log(apiResponse ? JSON.stringify(apiResponse) : 'empty response:' + eventId);
93
    throw new Error('State not found');
94
  }
95
  return JSON.parse(currentState) as PollState;
96
}
97